<?php
require_once 'CMS/Util.php';
require_once 'CMS/Mvc/BaseController.php';
require_once 'CMS/Mvc/BaseUserController.php';
require_once 'CMS/UserCommon.php';
require_once 'CMS/User.php';
require_once 'CMS/Language.php'; //include thu vien language

class NewsController extends BaseUserController{

	public function init(){
		parent::init();
		$tbSetting = new User_Model_Parameter();
		$temp = $tbSetting->selectSetting("config");
		$layout = unserialize($temp[0]["parameter_value"]);
		if($layout['config_template'] !="")
		{
			$this->_helper->layout()->setLayout($layout['config_template']);
			$_SESSION['config_template'] = $layout['config_template'];
		}
		else
		{
			$this->_helper->layout()->setLayout('layoutmain');
			$_SESSION['config_template'] = 'layoutmain';
		}
	}
	
	public function categoryAction(){
		$_SESSION['page_code'] = 'newscategory';
		$_GET['type'] = 2;
		//Start------Khai báo các parameter
		$dbshow = new User_Model_Parameter();
		//End--------Khai báo các parameter
		
		//Start------get type show
		$code = "Show_".$_SESSION['page_code'];
		$pageshow = $dbshow->selectSetting($code);
		//End--------get type show
		
		$_GET['show'] = $pageshow[0]["parameter_value"]; // khi có click change phần này.... sẽ thay đối số show kiểu list lấy từ xml vào đây
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$DefaultModules = $tbDefaultbarModule->selectAllModule("newscategory");
		foreach($DefaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("newscategory");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}		
		}
	}
	
	public function detailAction(){
		$_GET['type'] = 2;
		$_SESSION['page_code'] = 'newsdetail';
		
		$tbSidebarModule = new User_Model_SidebarModule();
		$Modules = $tbSidebarModule->selectAllModule();
		foreach($Modules as $module)
		{
			$database_show_widget [] = $module["module_code"];
			$database_order_widget [$module["module_code"]] =  $module["sort_order"];
		}
		
		$tbDefaultbarModule = new User_Model_DefaultModuleToPage();
		$DefaultModules = $tbDefaultbarModule->selectAllModule("newsdetail");
		foreach($DefaultModules as $dmodule)
		{
			$content_show_widget [] = $dmodule["module_code"];
			$content_order_widget [$dmodule["module_code"]] =  $dmodule["sort_order"];
		}
		
		$tbContentbarModule = new User_Model_ContentModuleToPage();
		// mac dinh homepage
		$ContentModules = $tbContentbarModule->selectAllModule("newsdetail");	
		foreach($ContentModules as $cmodule)
		{
			$content_show_widget [] = $cmodule["module_code"];
			$content_order_widget [$cmodule["module_code"]] =  $cmodule["sort_order"];
		}	
		
		$front     = Zend_Controller_Front::getInstance();
		$widgets = $front->getPlugins();
	
		foreach($widgets as $widget)
		{
			if(count($Modules) > 0){
				if($widget->name !="" && in_array($widget->name, $database_show_widget))
				{
					$widget->enable = 1;
					$widget->order = $database_order_widget[$widget->name];
				}
			}
			if(count($content_show_widget) > 0){
				if($widget->name !="" && in_array($widget->name, $content_show_widget))
				{
						$widget->enable = 1;
						$widget->order = $content_order_widget[$widget->name];
				}	
			}		
		}
	}
	public function postAction(){
		/*========== Start Load Language ==========*/
			
			$language = new Language(APPLICATION_PATH . '/modules/user/languages/news');
			$tbLanguage = new Language_Model_Language();
			$allLanguage = $tbLanguage->getAllLanguages();
			foreach ($allLanguage as $lang){
			$languages[] = array(
				'id' 	=> $lang['language_id'],
				'name'	=> $lang['name']
				);
			}
			$this->view->languages = $languages;
			if(isset($_SESSION['language']))
			{
				$language_id = $_SESSION['language'];
				$name = $tbLanguage->getNameLanguage($language_id);
				$language->load($name['name']);
				$this->view->nameLang = $name['name'];
			}
			else
			{
				$language->load('Default');
				$this->view->nameLang = "Default";
			}		
			/*========== End Load Language ==========*/
				
			/*========== Start Get Text ==============*/
			$this->view->textTitle 		= $language->get('text_title');
			$this->view->texttieude 		= $language->get('text_tieude');
			$this->view->textDM 		= $language->get('text_dm');
			$this->view->textDMO 		= $language->get('text_dmo');
			$this->view->textND 		= $language->get('text_nd');
			$this->view->textava 		= $language->get('text_ava');
			$this->view->textbutton 		= $language->get('text_button');
			
			$this->view->textError1 	= $language->get('error1');
			$this->view->textError2 	= $language->get('error2');
			$this->view->textError3 	= $language->get('error3');
			$this->view->textError4 	= $language->get('error4');
			$this->view->textError5 	= $language->get('error5');
			$this->view->textError6 	= $language->get('error6');
			/*========== End Text ==============*/		
		$this->_helper->layout->disableLayout();
		
		
		//Test mac dinh dang nhap
		
		$user = new User();
		$user->login("california", "anhnhoem");
		$session = new Zend_Session_Namespace('login.auth');
	
		//End - Test
		/*if(!isset($_SESSION["id_user"]))
		{
			$this->view->error_login = 1;
		}*/
		$error = 0;
		$error_title = array();
		$error_shortdes = array();
		if(isset($_GET["action"])&&($_GET["action"]=="insert")&&(!isset($this->view->error_login)))
		{
			if(!isset($_POST["news_title"]['Default'])||(strlen($_POST["news_title"]['Default'])<5))
			{
				$error_title['Default'] = 1;
				$error = 1 ;
			}
			if(!isset($_POST["news_short_description"]["Default"])||(strlen($_POST["news_short_description"]["Default"])<10))
			{
				$error_shortdes ['Default'] = 1;
				$error = 1 ;
			}
			foreach ($languages as $lang)
			{
				if(!isset($_POST["news_title"][$lang['name']])||(strlen($_POST["news_title"][$lang['name']])<5))
				{
					$error_title[$lang['name']]  = 1;
					$error = 1 ;
				}
				if(!isset($_POST["news_short_description"][$lang['name']])||(strlen($_POST["news_short_description"][$lang['name']])<10))
				{
					$error_shortdes[$lang['name']]  = 1;
					$error = 1 ;
				}
			}
			if(!isset($_POST["news_category"])||(!is_numeric($_POST["news_category"]))||($_POST["news_category"]<=0))
			{
				$this->view->error_cate = 1;
				$error = 1 ;
			}
			if(count($error_title) > 0 ) $this->view->error_title = $error_title;
			if(count($error_shortdes) > 0 ) $this->view->error_shortdes = $error_shortdes;
			
		}
		//End--------Check Input Parameter
		
		//Start------Khai báo các parameter
		$tbcategory = new User_Model_Categories();
		$tbthings = new User_Model_Things();
		$tbimagetothing = new User_Model_ImageToThing();
		$dateInt = new Util();
		//End--------Khai báo các parameter
		
		if(isset($_GET['path'])&&(is_numeric($_GET['path'])))
		{
			$news_information = $tbthings->getThingById($_GET['path']);
			if(count($news_information)>0)
			{
				$this->view->news = $news_information[0]['thing_id'];
				$title_news = unserialize($news_information[0]['title']);
				$short_des  = unserialize($news_information[0]['short_description']);
			}
			else
			{
				$this->error_news = 1;
			}
		}
		//Start------Get news Category
		if(isset($_GET['cate']))
		{
			$this->view->cate = $_GET['cate'];
			$Categoriesnews = array();
		}
		else
		{
			$Categoriesnews = $tbcategory->getLeafCategoriesbyType(2);
		}
		//End--------Get news Category
		
		if(isset($_GET["action"])&&($_GET["action"]=="insert")&&(!isset($this->view->error))&&($error == 0))
		{
			$array_title ["Default"] = $_POST['news_title']['Default'];
			$array_shortdes['Default'] = $_POST['news_short_description']['Default'];
			$array_description['Default'] = "";
			$array_description_table['Default'] = "";
			foreach ($languages as $lang)
			{
				$array_title[$lang['name']] = $_POST['news_title'][$lang['name']];
				$array_shortdes[$lang['name']] = $_POST['news_short_description'][$lang['name']];
				$array_description[$lang['name']] = "";
				$array_description_table[$lang['name']] = "";
			}
			$inserData = array(
								'category_id'	=>	$_POST["news_category"],
								'user_id'		=>	$session->id_user,
								'title'			=>	serialize($array_title),
								'short_description'	=>	serialize($array_shortdes),
								'description'	=>	serialize($array_description),
								'description_table'=> serialize($array_description_table),
								'avatar'		=>	$_POST["news_avatar"],
								'type'			=>	2,
								'update_date'	=>	$dateInt->get_time_now()
								);
			if(isset($_GET['path']))
			{
				if(is_numeric($_GET['path']))
				{
					$_SESSION['array_news_data'] = $inserData;
					unset($_SESSION['edit_thing']);
					unset($_SESSION['description_thing']);
					unset($_SESSION['description_table_thing']);
					unset($_SESSION['item']);
					unset($_SESSION['step_edit']);
					$this->_redirect("/admin/editor?item=thing&step=0&id=".$_GET['path']);
				}
				else
				{
					$result = -1;
				}
			}
			else 
			{
				$inserData['created_date']	=	$dateInt->get_time_now();
				$inserData['views']	=	0;
				$inserData['deleted']	=	0;
				$_SESSION['array_news_data'] = $inserData;
				unset($_SESSION['description_thing']);
				unset($_SESSION['description_table_thing']);
				$this->_redirect("/admin/editor?item=thing&step=0");
			}
			$this->view->error_process = $result;
		}
		$array_title = array();
		$array_shortdes = array();
		if(isset($_POST["news_title"]['Default']))
		{
			$array_title['Default'] = trim($_POST["news_title"]["Default"]);
		}
		else 
		{
			$array_title['Default'] = "";
		}
		if(isset($_POST["news_short_description"]["Default"]))
		{
			$array_shortdes ['Default']= trim($_POST["news_short_description"]["Default"]);
		}
		else 
		{
			$array_shortdes ['Default']="";
		}
		foreach($languages as $lang)
		{
			if(isset($_POST["news_title"][$lang['name']]))
			{
				$array_title[$lang['name']] =  trim($_POST["news_title"][$lang['name']]);
			}
			else 
			{
				$array_title[$lang['name']] = "";
			}	
			if(isset($_POST["news_short_description"][$lang['name']]))
			{
				$array_shortdes[$lang['name']] = trim($_POST["news_short_description"][$lang['name']]);
			}
			else 
			{
				$array_shortdes[$lang['name']] = "" ;
			}
		}
		if(isset($_POST["news_category"]))
		{
			$this->view->category = $_POST["news_category"];
		}
		else 
		{
			$this->view->category = 0;
		}
		if(isset($title_news))
		{
			$this->view->title = $title_news;
		}
		else
		{
			$this->view->title = $array_title;
		}
		if(isset($short_des))
		{
			$this->view->short_des = $short_des;
		}
		else
		{
			$this->view->short_des = $array_shortdes;
		}
		//Start------Truyền parameter qua View
		if(count($Categoriesnews)>0)
		{
			$this->view->Categoriesnews = $Categoriesnews;
		}
		else 
		{
			$this->view->Categoriesnews = array();
		}
		//End--------Truyền parameter qua View
		
		
	}
//Action Switch Type Show xử lý chức năng thay đổi phương thức hiển thị hỏi đáp
	public function switchtypeshowAction(){
		$this->_helper->layout->disableLayout();
		
		if(count($_GET) && isset($_GET["typeshow"]) && is_numeric($_GET["typeshow"]) && $_GET["typeshow"]>0) {
			
			$typeshow = $_GET["typeshow"];
			$data=array(
				'parameter_name' 	=> "Show_newscategory",
				'parameter_value' 	=> $typeshow
			);
			
			//Start------Khai báo các parameter
			$dbshow = new User_Model_Parameter();
			//End--------Khai báo các parameter
			
			//Start------Cập nhật phương thức hiển thị
			$result = $dbshow->updateSetting($data);
			//End--------Cập nhật phương thức hiển thị
			
			$this->_redirect("/news/category");
		}
		else {
			$this->_redirect("/news/category");
		}
	}
}